package com.android.aishangauction.activity.mine;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.aishangauction.R;
import com.android.aishangauction.app.BaseActivity;
import com.android.aishangauction.model.member.ForGetData;
import com.android.aishangauction.model.member.ForGetDataCallback;
import com.android.aishangauction.model.member.LoginResultData;
import com.android.aishangauction.model.member.LoginResultDataCallback;
import com.android.aishangauction.model.member.SendCodeData;
import com.android.aishangauction.model.member.SendCodeDataCallback;
import com.android.aishangauction.utils.ConstantsUrl;
import com.android.aishangauction.utils.HttpUtils;
import com.android.aishangauction.utils.MyLog;
import com.android.aishangauction.utils.ObjectUtils;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by Administrator on 2017/9/5.
 */

public class FindPwActivity extends BaseActivity {


    @BindView(R.id.main_top_back)
    ImageView back;
    @BindView(R.id.ll_sign_phone)
    EditText llSignPhone;
    @BindView(R.id.ll_sign_code)
    EditText llSignCode;
    @BindView(R.id.ll_sign_code_send)
    TextView llSignCodeSend;
    @BindView(R.id.ll_sign_pd)
    EditText llSignPd;
    @BindView(R.id.ll_sign_pd_confirm)
    EditText ll_sign_pd_confirm;
    @BindView(R.id.register)
    TextView register;
    @BindView(R.id.ll_sign_code_img)
    EditText ll_sign_code_img;
    @BindView(R.id.web_sign_code_send)
    WebView web_sign_code_send;
    private boolean networkConnected;
    private TimeCount time;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_findps);
        ButterKnife.bind(this);
        initUI();
        time = new TimeCount(60000, 1000);
    }

    private boolean isCheck = true;

    private void initUI() {
        String path=ConstantsUrl.domain+ConstantsUrl.MEMBERWELCOMSCODE;
        web_sign_code_send.loadUrl(path);
    }

    //登录
    private void PostLogin(String phone, String pd) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORLOGIN;
        HashMap<String, String> map = new HashMap<>();
        MyLog.e("地址", address);
        map.put("username", phone);
        map.put("password", pd);
        if (networkConnected) {
            HttpUtils.post(address, map, new LoginResultDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {
                }

                @Override
                public void onResponse(LoginResultData response, int id) {
                    if (response.getCode() == 0) {
                        //保存用户数据
                        PostLoginThree(response.getData().getUNAME(), response.getData().getAvatar(), response.getData().getUID(), response.getData().getUPSW());
                    } else {
                        ObjectUtils.toast(FindPwActivity.this, response.getMsg());
                    }

                }
            });

        } else {

            ObjectUtils.toast(this, "网络连接出错了");
        }

    }

    private void PostSign(String phone, String code, String pd) {
        networkConnected = ObjectUtils.isNetworkConnected(this);
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORFORGETPW;
        MyLog.e("地址", address);
        if (networkConnected) {
            HashMap<String, String> map = new HashMap<>();
            map.put("mobile", phone);
            map.put("sms_code", code);
            map.put("password", pd);
            HttpUtils.post(address, map, new ForGetDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(ForGetData response, int id) {
                    if (response.getCode() == 0) {
                        //保存用户数据
                      //  PostLoginTwo(response.getData().getUNAME(), response.getData().getAvatar(), response.getData().getUID(), response.getData().getUPSW());
                        ObjectUtils.toast(FindPwActivity.this, "保存成功");
                        finish();
                    } else {
                        ObjectUtils.toast(FindPwActivity.this, response.getMsg());
                    }

                }
            });

        } else {

            ObjectUtils.toast(this, "网络连接出错了");
        }

    }


    //发送验证码
    private void SendCode(String phone) {
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORSENDMESSAGE;
        HashMap<String, String> map = new HashMap<>();
        map.put("mobile", phone);
        map.put("act", "sms_chpass");
        networkConnected = ObjectUtils.isNetworkConnected(this);
        if (networkConnected) {

            HttpUtils.post(address, map, new SendCodeDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(SendCodeData response, int id) {

                    ObjectUtils.toast(FindPwActivity.this, response.getMsg());
                    if (response.getCode() == 0) {
                        time.start();
                    }

                }
            });

        } else {

            ObjectUtils.toast(this, "网络连接出错了");
        }

    }

String PHPSESSID;
    @OnClick({R.id.main_top_back, R.id.ll_sign_code_send, R.id.register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_top_back:
                finish();
                break;
            case R.id.ll_sign_code_send:
                String sign_phone = llSignPhone.getText().toString().trim();
                if ("".equals(sign_phone)) {
                    ObjectUtils.toast(this, "请输入手机号码");
                    return;
                }
                String code=ll_sign_code_img.getText().toString();
                CookieManager cookieManager = CookieManager.getInstance();
                String CookieStr = cookieManager.getCookie(ConstantsUrl.domain+ConstantsUrl.MEMBERWELCOMSCODE);
                MyLog.e("inest","CookieStr="+CookieStr);
                PHPSESSID= CookieStr.substring(CookieStr.indexOf("PHPSESSID=")).replace("PHPSESSID=","");;
                SendCode(sign_phone,code,PHPSESSID);

//                SendCode(sign_phone);
                break;
            case R.id.register:
//                if (isCheck) {
//                    String lgphone = llLoginPhone.getText().toString().trim();
//                    String lgpd = llLoginPd.getText().toString().trim();
//                    if ("".equals(lgphone)) {
//                        ObjectUtils.toast(this, "请输入账号");
//                        return;
//                    }
//                    if ("".equals(lgpd)) {
//                        ObjectUtils.toast(this, "请输入密码");
//                        return;
//                    }
//
//
//                } else {
                String sgphone = llSignPhone.getText().toString().trim();
                String sgcode = llSignCode.getText().toString().trim();
                String lgpd = llSignPd.getText().toString().trim();
                String lgpdcf =      ll_sign_pd_confirm.getText().toString().trim();
                if ("".equals(sgphone)) {
                    ObjectUtils.toast(this, "请输入手机号");
                    return;
                }
                if ("".equals(sgcode)) {
                    ObjectUtils.toast(this, "请输入验证码");
                    return;
                }
                if ("".equals(lgpd)) {
                    ObjectUtils.toast(this, "请输入密码");
                    return;
                }
                if ("".equals(lgpdcf)) {
                    ObjectUtils.toast(this, "请输入密码");
                    return;
                }
                if (!lgpd.equals(lgpdcf)) {
                    ObjectUtils.toast(this, "两次密码输入请保持一致");
                    return;
                }
                PostSign(sgphone,sgcode,lgpd);
                //    }

                break;
        }
    }

    //登录并保存
    private void PostLoginThree(String uname, String avatar, String uid, String upsw) {
        SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(ConstantsUrl.USERDATA_NAME, uname);
        edit.putString(ConstantsUrl.USERDATA_AVATAR, avatar);
        edit.putString(ConstantsUrl.USERDATA_UID, uid);
        edit.putString(ConstantsUrl.USERDATA_UPSW, upsw);
        edit.putInt(ConstantsUrl.USERDATA_TYPE, 0);
        edit.commit();
        ObjectUtils.toast(FindPwActivity.this, "登录成功");
        LoginActivity.intance.finish();
        finish();
    }
    //注册并保存
    private void PostLoginTwo(String uname, String avatar, String uid, String upsw) {
        SharedPreferences sp = getSharedPreferences(ConstantsUrl.USERDATA, 0);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString(ConstantsUrl.USERDATA_NAME, uname);
        edit.putString(ConstantsUrl.USERDATA_AVATAR, avatar);
        edit.putString(ConstantsUrl.USERDATA_UID, uid);
        edit.putString(ConstantsUrl.USERDATA_UPSW, upsw);
        edit.putInt(ConstantsUrl.USERDATA_TYPE, 0);
        edit.commit();
        ObjectUtils.toast(FindPwActivity.this, "登录成功");
        // SignActivity.finish();
        finish();
    }
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            llSignCodeSend.setText("重新获取验证码");
            llSignCodeSend.setTextColor(Color.parseColor("#ffffff"));
            llSignCodeSend.setBackgroundResource(R.drawable.corner_red_bg);
            llSignCodeSend.setClickable(true);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            llSignCodeSend.setClickable(false);// 防止重复点击
            llSignCodeSend.setTextColor(Color.parseColor("#5a5a5a"));
            llSignCodeSend.setBackgroundResource(R.drawable.corner_gray_bg);
            llSignCodeSend.setText("重新发送(" + millisUntilFinished / 1000 + ")秒");
        }
    }

    //发送验证码
    private void SendCode(String phone,String code,String CookieStr) {
        String address = ConstantsUrl.domain + ConstantsUrl.MEMBERORSENDMESSAGE;
        HashMap<String, String> map = new HashMap<>();
        map.put("mobile", phone);
        map.put("scode",code);
        map.put("act", "sms_chpass");
        map.put("PHPSESSID", CookieStr);

        HashMap<String, String> headers = new HashMap<>();
//        headers.put("PHPSESSID", CookieStr);
        MyLog.e("inest","code="+code+"  "+phone+"   CookieStr="+CookieStr);
        networkConnected = ObjectUtils.isNetworkConnected(this);
        if (networkConnected) {

            HttpUtils.post(address ,headers,map, new SendCodeDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }

                @Override
                public void onResponse(SendCodeData response, int id) {

                    ObjectUtils.toast(FindPwActivity.this, response.getMsg());
                    if (response.getCode() == 0) {
                        time.start();
                        String path=ConstantsUrl.domain+ConstantsUrl.MEMBERWELCOMSCODE;
                        web_sign_code_send.loadUrl(path);

                    }

                }
            });

        } else {

            ObjectUtils.toast(this, "网络连接出错了");
        }

    }
}
